<script lang="ts" setup>
import { ref, reactive, onMounted, watch,type VNode,h} from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  type FormRules,
  useMessage,
  NScrollbar,
  NSpin,
  NImageGroup,
  NImage,
  type SelectOption,
  NTooltip
} from 'naive-ui'
import InfoBatch from '@/components/CollectProcess/InfoBatch/index.vue'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import BasicInfo from '@/components/CollectProcess/BasicInfo.vue'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import useSubmit,{defaultVersionTypeValue,defaultVersionTypeKey} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
const { dfInst, formData, createVars,submitLoading,submit:submitR } = useSubmit()
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null },
  typeIn: { type: Number, default: () => null },
  batchCode: { type: String, default: () => null },
})
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const array = props?.id?.split(',') || []
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null,
    subItemCode: null
  }
})
const renderOption1 = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
)
const fileImgList:any = ref([])//附件数组
const optionInPosition0 = ref([])
const optionInPosition1 = ref([])
const optionInPosition2 = ref([])
const optionInPosition3 = ref([])
const optionInPosition4 = ref([])
const optionInPosition5 = ref([])
const formRules: FormRules = {
  itemsStaging: {
    assetCode: {
      required: false,
      trigger: ['blur', 'input'],
      validator: () => {
        if (!form.itemsStaging.assetCode) return
        if (!Number.isFinite(Number(form.itemsStaging.assetCode))) {
          return new Error('资产码必须为数字')
        }
        if (form.itemsStaging.assetCode.toString().length > 18) {
          return new Error('资产码最多18位')
        }
        return true
        // if (!/^[0-9]{1,18}$/g.test(form.itemsStaging.assetCode)) return new Error('资产码最多18位')
      }
    },
    // fifthLevelCode: {
    //   required: optionInPosition4.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // sixthLevelCode: {
    //   required: optionInPosition5.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    firstLevelCode: {
      // required: optionInPosition0.value.length > 0 ? true : false,
      required: true,
      trigger: ['blur', 'change'],
      type: 'any',
      message: '不能为空'
    }
    // secondLevelCode: {
    //   required: optionInPosition1.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // threeLevelCode: {
    //   required: optionInPosition2.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // fourthLevelCode: {
    //   required: optionInPosition3.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // }
  }
}

const handleUpdateAssetCode = (e: any) => {
  if (e && e.length > 18) {
    form.itemsStaging.assetCode = e.slice(0, 18)
    return message.error('资产码最多18位')
  }
  form.itemsStaging.assetCode = e
}

const getFirstFn = async (id: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listOptionsByParentId',
    override: {
      params: {
        parentId: id
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data || []
}

const changeOptionFn = (e: any, type: any) => {
  switch (type) {
    case 1: {
      form.itemsStaging.secondLevelCode = null
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition1)
      break
    }
    case 2: {
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition2)
      break
    }
    case 3: {
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition3)
      break
    }
    case 4: {
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition4)
      break
    }
    case 5: {
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition5)
      break
    }
  }
}
const formInst = ref<FormInst | null>(null)
const submit = async () => {
  const validate = await Promise.all([
    // 暂时未使用
    // new Promise((resolve, reject) => {
    //   formInst.value?.validate((error) => {
    //     if (error) return reject(error)
    //     resolve(true)
    //   })
    // }),
    new Promise((resolve, reject) => {
      userFormRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])

  // if (!validate.every(Boolean)) return

  // if (!formInst.value) return
  // await formInst.value?.validate()

  if (!userFormRef.value) return
  await userFormRef.value.validate()
  const pass = await submitR()
  if (!pass) return
  loading.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'saveFirstCatalogInfo',
    override: {
      data: {
        id: form.id,
        itemsStaging: form.itemsStaging,
        catalogInfo: {
          contentJson: JSON.stringify(formData.value || {}),
          id: form.id,
          subItemCode: form.subItemCode
        }
      }
    }
  })
  loading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  routeReplace()
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const spinShow = ref(false)
const itemTypeCode = ref(null)
const findDetail = async () => {
  spinShow.value = true
  sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsInfo',
    uri: {
      id: props.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    spinShow.value = false
    await getFirstFn(0, optionInPosition0)
    await getFirstFn(res.data?.itemsStaging?.firstLevelCode, optionInPosition1)
    await getFirstFn(res.data?.itemsStaging?.secondLevelCode, optionInPosition2)
    await getFirstFn(res.data?.itemsStaging?.threeLevelCode, optionInPosition3)
    await getFirstFn(res.data?.itemsStaging?.fourthLevelCode, optionInPosition4)
    await getFirstFn(res.data?.itemsStaging?.fifthLevelCode, optionInPosition5)

    keysOf(res.data).forEach((e) => {
      form[e] = res.data[e] as never
    })
    itemTypeCode.value = res.data?.itemTypeCode
    await getInfo(res.data?.subItemCode, res.data?.itemCode)
    // res.data?.itemTypeCode && queryJsonBM(res.data?.itemTypeCode)

 
    form.itemsStaging.subItemCode = res.data?.subItemCode || null
    form.itemsStaging.assetCode =
      res.data?.itemsStaging?.assetCode || res.data?.itemsStaging?.assetCode == 0
        ? res.data?.itemsStaging?.assetCode
        : null
    form.itemsStaging.firstLevelCode = res.data?.itemsStaging?.firstLevelCode
    form.itemsStaging.secondLevelCode = res.data?.itemsStaging?.secondLevelCode
    form.itemsStaging.threeLevelCode = res.data?.itemsStaging?.threeLevelCode
    form.itemsStaging.fourthLevelCode = res.data?.itemsStaging?.fourthLevelCode
    form.itemsStaging.fifthLevelCode = res.data?.itemsStaging?.fifthLevelCode
    form.itemsStaging.sixthLevelCode = res.data?.itemsStaging?.sixthLevelCode
  })
}

const otherJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_CB.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
// const formData = ref({} as any)
const getInfo = async (subItemCode: any, code: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfoByCode',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return
    formData.value = JSON.parse(res.data?.catalogInfo || `{}`)
    if (formData.value['BMCOM006']) formData.value['BMCOM006'] = formData.value['BMCOM006'].split('>').pop()
    checkIsDetail(code) //编辑-空值赋值
  })
}
const handleUpdateFormData = (key: string, value: unknown) => {
  formData.value[key] = value
}
const keyToLabel = [
  { value: ['其他'], label: 'MNTS04' },
  { value: ['T002'], label: 'MNTS05' },
  { value: ['T009', 'T008', 'T003'], label: 'MNTS10' },
  { value: ['T001002', 'T001003'], label: 'MNTS12' },
  { value: ['T001001'], label: 'BMTS11' }
]
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    const { data } = res
    res.data?.fileList?.map((i: any) => {
        fileImgList.value.push({
          name: i.name,
          url: i.path,
          status: 'finished',
          id: i.id
        })
      })
    data.itemTypeCode && getCodeFn(data.itemTypeCode, data.itemName)
  } catch (error) {
    // console.error(error)
  } finally {
  }
}
// 获取对应的正题名字段
const getCodeFn = (e: any, target:any) => {
  // let name = null
  // debugger
  // keyToLabel.map((it) => {
  //   it.value.map((i) => {
  //     if (e.includes(i)) {
  //       name = it.label
  //     }
  //   })
  // })
  // if (!formData.value?.[name]) {
  //   //没值才赋值
  //   if (name) {
  //     //找到就有
  //     formData.value[name] = target
  //   } else {
  //     //没找到默认其他
  //     formData.value['MNTS04'] = target
  //   }
  // }
  formData.value['BMCOM007'] = target
   
}
watch(
  () => route,
  () => {
    if (props.id) {
      if (route.name == 'updateInitCompilationSelf' || route.name == 'detailInitCompilation') {
        fileImgList.value = []
       findDetail()
      }
    }
  },
  { deep: true, immediate: true }
)
// onMounted(async () => {
//   // 修改回显
//   if (props.id) {
//     findDetail()
//     checkIsDetail()
//   }
// })
</script>

<template>
  <DetailFormProvider>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div class="topTitle">批次信息</div>
            <!-- <BasicInfo
              :id="props.id"
              :type-show="props.typeShow"
              :code="props.code"
            ></BasicInfo> -->
            <InfoBatch :key='props.batchCode' :id="props.batchCode" />

            <div class="topTitle">初编信息</div>
            <div class="dynamic-form-demo">
          <DynamicFormComponent ref="dfInst" :data="formData" v-if='itemTypeCode' :itemTypeCode='itemTypeCode' :isCB='true' :disabled="props?.typeShow == 1" :createVars="createVars" />
        </div>
            <!-- <DynamicPageForm
              ref="formInst"
              :form-model="otherJson"
              :model="formData"
              :form-data="formData"
              label-placement="left"
              require-mark-placement="left"
              label-width="140rem"
              :disabled="props?.typeShow == 1"
              @update:value="handleUpdateFormData"
            /> -->
            <div class="detailinlineStyle">
              <span v-show='fileImgList?.length > 0' style='margin-right:10px'>附件:</span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image width="100" height="100" :src="i.url" :key="i.id" v-for="i in fileImgList" />
                  </n-space>
                </n-image-group>
              </div>
            </div>
            <div class="topTitle">入库</div>
            <NForm
              :model="form"
              :rules="formRules"
              ref="userFormRef"
              label-placement="left"
              label-width="140rem"
              require-mark-placement="left"
            >
              <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
                <NFormItem
                  label="唯一编号:"
                  path="itemsStaging.subItemCode"
                >
                  <NInput
                    :value="form.itemsStaging.subItemCode"
                    class="inputWH"
                    :show-button="false"
                    :disabled="true"
                  />
                </NFormItem>
                <!-- <NFormItem
                  label="资产码:"
                  path="itemsStaging.assetCode"
                >
                  <NInput
                    :value="form.itemsStaging.assetCode"
                    @update:value="handleUpdateAssetCode"
                    class="inputWH"
                    :show-button="false"
                    :disabled="props?.typeShow == 1 || props.typeIn == 2"
                  />
                </NFormItem> -->
              </div>
              <NFormItem
                label="流水号:"
                path="itemsStaging.serialNumber"
              >
                <NInput
                  v-model:value="form.itemsStaging.serialNumber"
                  class="inputWH"
                  :disabled="props?.typeShow == 1"
                />
              </NFormItem>
              <NSpace>
                <NFormItem
                  label="入库位置:"
                  path="itemsStaging.firstLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.firstLevelCode"
                    placeholder="位置1"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition0"
                    @update-value="(e) => changeOptionFn(e, 1)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="itemsStaging.secondLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.secondLevelCode"
                    placeholder="位置2"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition1"
                    @update-value="(e) => changeOptionFn(e, 2)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="itemsStaging.threeLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.threeLevelCode"
                    placeholder="位置3"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition2"
                    @update-value="(e) => changeOptionFn(e, 3)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="itemsStaging.fourthLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.fourthLevelCode"
                    placeholder="位置4"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition3"
                    @update-value="(e) => changeOptionFn(e, 4)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="itemsStaging.fifthLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.fifthLevelCode"
                    placeholder="位置5"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition4"
                    @update-value="(e) => changeOptionFn(e, 5)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
                <NFormItem
                  label=""
                  path="itemsStaging.sixthLevelCode"
                >
                  <NSelect
                    v-model:value="form.itemsStaging.sixthLevelCode"
                    placeholder="位置6"
                    class="inputWHmin"
                    filterable
                    clearable
                    :options="optionInPosition4"
                    @update-value="(e) => changeOptionFn(e, 6)"
                    :render-option="renderOption1"
                    :disabled="props?.typeShow == 1"
                  />
                </NFormItem>
              </NSpace>
            </NForm>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  </DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        {{ props?.typeShow == 0 ? '取消' : '关闭' }}
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="submit"
        :loading="loading"
        v-if="props?.typeShow == 0"
      >
        确定
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .dynamic-form-demo {
    background-color: #e1e1e1;
    padding: 30px 45px 10px;
    // height:300px;
  }
  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }
}
.detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 20px;
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
